package com.xjrsoft.module.oa.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.annotation.XjrLog;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.enums.IsReadTypeEnum;
import com.xjrsoft.common.enums.MessageType;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageInput;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.erpModel.caseErpSupplier.vo.CaseErpSupplierPageVo;
import com.xjrsoft.module.oa.dto.AddNewsDto;
import com.xjrsoft.module.oa.dto.MessageListDto;
import com.xjrsoft.module.oa.dto.NewsPageDto;
import com.xjrsoft.module.oa.entity.Message;
import com.xjrsoft.module.oa.entity.News;
import com.xjrsoft.module.oa.service.IMessageService;
import com.xjrsoft.module.oa.vo.MessageBoxVo;
import com.xjrsoft.module.oa.vo.MessageListVo;
import com.xjrsoft.module.oa.vo.MessageVo;
import com.xjrsoft.module.oa.vo.NewsPageVo;
import com.xjrsoft.module.organization.dto.ResetPasswordDto;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.organization.vo.UserVo;
import com.xjrsoft.module.system.entity.File;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 消息状态 前端控制器
 * </p>
 *
 * @author zlf
 * @since 2022-06-16
 */
@RestController
@RequestMapping(GlobalConstant.OA_MODULE_PREFIX + "/message")
@Api(value = GlobalConstant.OA_MODULE_PREFIX + "/message", tags = "消息")
@AllArgsConstructor
public class MessageController {

    private IMessageService messageService;


    @GetMapping("/list")
    @ApiOperation(value = "获取消息数据")
    public R list(MessageListDto dto) {
        Wrapper<Message> wrapper = Wrappers.<Message>query().lambda()
                .eq(Message::getUserId, StpUtil.getLoginIdAsLong())
//                .like(StrUtil.isNotBlank(dto.getKeyword()), Message::getMessageContent, dto.getKeyword())
                .orderByDesc(Message::getSendTime)
                .select(Message.class, x -> VoToColumnUtil.fieldsToColumns(MessageListVo.class).contains(x.getProperty()));

        PageInput pageInput = new PageInput();
        //最新数据
        pageInput.setLimit(0);
        //只取5条数据
        pageInput.setSize(5);
        IPage<Message> page = messageService.page(ConventPage.getPage(pageInput), wrapper);
        List<MessageListVo> vos = BeanUtil.copyToList(page.getRecords(), MessageListVo.class);

        for (MessageListVo vo : vos) {


            //如果是同一天
            if (
                    vo.getSendTime().getYear() == LocalDateTime.now().getYear() &&
                            vo.getSendTime().getMonth() == LocalDateTime.now().getMonth() &&
                            vo.getSendTime().getDayOfYear() == LocalDateTime.now().getDayOfYear()
            ) {
                if (vo.getSendTime().getMinute()>10){
                    vo.setTimeFormat(StrUtil.toString(vo.getSendTime().getHour()) + StringPool.COLON + StrUtil.toString(vo.getSendTime().getMinute()));
                }
                else {
                    char zeroChar = '0';
                    vo.setTimeFormat(StrUtil.toString(vo.getSendTime().getHour()) + StringPool.COLON + StrUtil.fillBefore(StrUtil.toString(vo.getSendTime().getMinute()),zeroChar,2));
                }
            } else {
                Duration between = LocalDateTimeUtil.between(vo.getSendTime(), LocalDateTime.now());

                vo.setTimeFormat(StrUtil.toString(between.toDays() == 0 ? 1 : between.toDays()) + "天前");
            }


//            if(between.toDays() < 2){
//                vo.setTimeFormat(StrUtil.toString(vo.getSendTime().getHour()) + StringPool.COLON + StrUtil.toString(vo.getSendTime().getMinute()));
//            }
//            if(between.toDays() >= 2){
//                vo.setTimeFormat(StrUtil.toString(between.toDays()) + "天前");
//            }
        }
        return R.ok(vos);
    }


    @GetMapping("/box")
    @ApiOperation(value = "获取系统通知")
    public R box(PageInput dto) {
        Wrapper<Message> wrapper = Wrappers.<Message>query().lambda()
                .eq(Message::getUserId, StpUtil.getLoginIdAsLong())
                .eq(Message::getMessageType,MessageType.MESSAGE_SEND.getCode())
                .orderByDesc(Message::getSendTime)
                .select(Message.class, x -> VoToColumnUtil.fieldsToColumns(MessageListVo.class).contains(x.getProperty()));

        IPage<Message> page = messageService.page(ConventPage.getPage(dto), wrapper);
        List<Message> list = page.getRecords();
        List<MessageBoxVo> messageBoxVos = BeanUtil.copyToList(list, MessageBoxVo.class);
        PageOutput<MessageBoxVo> output = new PageOutput<>();
        output.setCurrentPage(dto.getLimit());
        output.setPageSize(dto.getSize());
        output.setTotal(Integer.parseInt(String.valueOf(page.getTotal())));
        output.setList(messageBoxVos);
        return R.ok(output);
    }


    @GetMapping(value = "/info")
    @ApiOperation(value = "消息详情")
    public R info(@RequestParam Long id) {
        Message msg = messageService.getById(id);
        if (msg == null) {
            R.error("找不到此消息！");
        }
        return R.ok(BeanUtil.toBean(msg, MessageVo.class));
    }

    @PutMapping("/read-all-message")
    @ApiOperation(value = "将所有工作流未读消息改为已读")
    public R readAllMessage() {
        //1、获取用户id
        Long userId = StpUtil.getLoginIdAsLong();
        //2、根据用户id和消息类型修改对应的是否已读字段为已读
        Wrapper<Message> wrapper = Wrappers.<Message>update().lambda().set(Message::getIsRead, IsReadTypeEnum.READ.getCode())
                .eq(Message::getUserId, userId).eq(Message::getMessageType, MessageType.APPROVE.getCode()).or().eq(Message::getMessageType, MessageType.CIRCULATED.getCode());
        messageService.update(wrapper);
        return R.ok();
    }

    @PutMapping("/read-message")
    @ApiOperation(value = "将单条未读消息改为已读")
    public R readMessage(@RequestBody ResetPasswordDto dto) {
        Message message = new Message();
        message.setId(dto.getId());
        message.setIsRead(IsReadTypeEnum.READ.getCode());
        //将是否已读类型改为已读
        messageService.updateById(message);
        return R.ok();
    }

    @PutMapping("/read-all-schedule-message")
    @ApiOperation(value = "将所有日程未读消息改为已读")
    public R readAllScheduleMessage() {
        //1、获取用户id
        Long userId = StpUtil.getLoginIdAsLong();
        //2、根据用户id和消息类型修改对应的是否已读字段为已读
        Wrapper<Message> wrapper = Wrappers.<Message>update().lambda().set(Message::getIsRead, IsReadTypeEnum.READ.getCode())
                .eq(Message::getUserId, userId).eq(Message::getMessageType, MessageType.SCHEDULE.getCode());
        messageService.update(wrapper);
        return R.ok();
    }
}
